/*


The MIT License

Copyright (c) 2008 Mohamed El-Shinnawy

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

#import "iTalyView.h"

@implementation iTalyView

- (void) loadSavedPhrases{
	NSLog(@"Inside loadSavedPhrases");

	NSMutableArray *oEnglishPhrases = [[NSUserDefaults standardUserDefaults] objectForKey:@"english"];
	NSMutableArray *oPronounciation = [[NSUserDefaults standardUserDefaults] objectForKey:@"translations"];

	[[NSUserDefaults standardUserDefaults] synchronize];

	BOOL load1 = NO, load2 = NO;

	if(oEnglishPhrases != nil){
		NSLog(@"oEnglishPhrases != nil");
		NSLog(@"Phrases count = %i", oEnglishPhrases.count);
		load1 = YES;
	}

	if(oPronounciation != nil){
		NSLog(@"oPronounciation != nil");
		NSLog(@"Pronounciation count = %i", oPronounciation.count);
		load2 = YES;
	}

	if(load1 && load2 && oEnglishPhrases.count == oPronounciation.count){
		NSLog(@"Will now assign member variables!");
		mEnglishPhrases = [[NSMutableArray alloc] init];
		[mEnglishPhrases addObjectsFromArray:oEnglishPhrases];
		mPronounciation = [[NSMutableArray alloc] init];
		[mPronounciation addObjectsFromArray:oPronounciation];
		NSLog(@"Success!");
	}
}

- (void) savePhrases{
	NSLog(@"Inside savePhrases");
	[self clearPhrases];
	NSLog(@"Cleared old phrases!");
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSLog(@"Retrieved defaults");
	[defaults setObject:mEnglishPhrases forKey:@"english"];
	[defaults setObject:mPronounciation forKey:@"translations"];
	NSLog(@"Successfully set the new dictionary");
	if([defaults synchronize]) {
		NSLog(@"Saved Successfully!");
	} else {
		NSLog(@"Problem while saving! help!");
	}
}

- (void) clearPhrases{
	NSLog(@"Inside clearPhrases");

	[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"english"];
	[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"translations"];

	if([[NSUserDefaults standardUserDefaults] synchronize]){
		NSLog(@"Cleared correctly!");
	} else {
		NSLog(@"Problem while deleting!");
	}
}

- (NSMutableArray *) getResults:(NSString *)aSearchTerm{
	if(aSearchTerm == nil || aSearchTerm.length ==0) return nil;
	NSMutableArray *results = [[NSMutableArray alloc] init];
	int i = 0,count = [mPronounciation count];
	Phrase *p = nil;
	if([aSearchTerm isEqualToString:@"~"]){	
		for(i = 0; i < count; i++){
			p = [[Phrase alloc] initWithPronounciation:(NSString *)[mPronounciation objectAtIndex:i] withDescription:(NSString *)[mEnglishPhrases objectAtIndex:i]];
			[results addObject:p];
		}
	}
	return results;
}

- (void) savePhraseWithDescription:(NSString *)aDescription withPronounciation:(NSString *)aPronounciation{
	NSLog(@"Inside savePhraseWithDescription: withPronounciation:");
	NSLog(@"English: %@, Pronounciation: %@", aDescription, aPronounciation);
	NSLog(@"English Array = %@", mEnglishPhrases);
	[mEnglishPhrases addObject:aDescription];
	NSLog(@"Added description!");
	[mPronounciation addObject:aPronounciation];
	NSLog(@"Added pronounciation!");
	[self savePhrases];
}

- (void) loadResultsInTable{
	[mResultsTableView reloadData];
}

- (void)applicationDidFinishLaunching:(NSNotification *)notification{
	mIsAddingKeyboard = YES;
	NSLog(@"Launching App");

	//Sustain a little bit longer the splash screen
	sleep(1);

	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;

	//Initialize Window
	mWindow = [[UIWindow alloc] initWithContentRect: [UIHardware fullScreenApplicationContentRect]];
	//Initialize View
	mView = [[UIView alloc] initWithFrame:[mWindow bounds]];
	//Initialize Keyboard
	mKeyboard = [[UIKeyboard alloc] initWithFrame:CGRectMake(rect.origin.x, 
								rect.size.height - [UIKeyboard defaultSize].height, 
								rect.size.width, 
								[UIKeyboard defaultSize].height)];
	mIsKeyboardVisible = NO;
	//Initialize Navigation Bar
	mNavigationBar = [[UINavigationBar alloc] init];
	[mNavigationBar setFrame:CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 45.0f)];
	[mNavigationBar showLeftButton:@"About" withStyle:1 rightButton:@"Add" withStyle:0];
	[mNavigationBar setDelegate:self];
	[mNavigationBar setBarStyle:0];
	//Initialize Navigation Bar Title & Add it to the Navigation Bar
	UINavigationItem *oTitle = [[UINavigationItem alloc] initWithTitle:@"iTally"];
	[mNavigationBar pushNavigationItem:oTitle];
	//Add the Navigation Bar to the View
	[mView addSubview: mNavigationBar];
	//Initialize Search Navigation Bar
	mSearchNavigationBar = [[UINavigationBar alloc] init];
	[mSearchNavigationBar setFrame:CGRectMake(rect.origin.x, rect.origin.y+45.0f, rect.size.width, [UISearchField defaultHeight])];
	[mSearchNavigationBar setDelegate:self];
	[mSearchNavigationBar setBarStyle:1];
	//Add the Search Navigation Bar to the View
	[mView addSubview: mSearchNavigationBar];
	//Initialize Search Text Field
	mSearchBoxView = [[UISearchField alloc] initWithFrame:CGRectMake(rect.origin.x, rect.origin.y+45.0f, rect.size.width, [UISearchField defaultHeight])];
	[mSearchBoxView setDisplayEnabled:YES];
	[mSearchBoxView setBorderStyle:3];
	[mSearchBoxView setClearButtonStyle:2];
	[mSearchBoxView setFont: [GSFontCreateWithName("Helvetica", 0, 11.0f) autorelease]];
        [[mSearchBoxView textTraits] setReturnKeyType:6];
        [[mSearchBoxView textTraits] setEditingDelegate:self];
        [mSearchBoxView setPaddingTop:5];
	[mSearchBoxView setDelegate:self];
        [mSearchBoxView setPlaceholder:@"type to search..."];
	[mSearchBoxView attachFieldEditor: mKeyboard];
	[mSearchBoxView becomeFirstResponder];
	//Add the Search Text Field to the View
	[mView addSubview: mSearchBoxView];
	//Initialize the Results Table
	mResultsTableView = [[UITable alloc] initWithFrame:CGRectMake(rect.origin.x, 
								      rect.origin.y+45.0f+[UISearchField defaultHeight], 
								      rect.size.width, 
								      rect.size.height-45.0f-[UISearchField defaultHeight])];
	UITableColumn *oCol = [[UITableColumn alloc] initWithTitle:@"Results" identifier:@"results" width:rect.size.width];
	[mResultsTableView addTableColumn:oCol];
	[mResultsTableView setSeparatorStyle:1];
	[mResultsTableView setRowHeight:75];
	[mResultsTableView setDataSource:self];
	[mResultsTableView setDelegate:self];
	NSLog(@"Initialized table");

	//Load saved phrases
	mEnglishPhrases = nil;
	mPronounciation = nil;
	[self loadSavedPhrases];
	//Initialize Data Structures
	if(mEnglishPhrases == nil){
		NSLog(@"English Phrases were empty!");
		mEnglishPhrases = [[NSMutableArray alloc] init];
	}
	if(mPronounciation == nil){
		NSLog(@"Pronounciations were empty!");
		mPronounciation = [[NSMutableArray alloc] init];
	}

	//Populate the Results Table
	mResults = [self getResults:@"~"];
	if(mResults != nil){
		NSLog(@"Results = %@", mResults);
		[self loadResultsInTable];
	} else {
		NSLog(@"Empty results!");
	}

	// Add the Results Table to the view
	[mView addSubview: mResultsTableView];
	//Add Keyboard to View
	[mView addSubview: mKeyboard];

	[mWindow orderFront:self];
	[mWindow makeKey:self];
	[mWindow setContentView:mView];
	mIsAddingKeyboard = NO;
}

- (UIView *) getView{
	return mView;
}

- (void)setView:(UIView *) aView{
	mView = aView;
}

- (void) showAlert:(NSString *)aTitle withMessageBody:(NSString *)aMessageBody{
	//Method for showing modal alert boxes
	NSMutableArray *buttons = [[NSMutableArray alloc] init];
	[buttons addObject:[NSString stringWithString:@"OK"]];
	UIAlertSheet *alert = [[UIAlertSheet alloc]
		initWithTitle:aTitle
		buttons:buttons
		defaultButtonIndex:0
		delegate:self
		context:self];
	[alert setBodyText:aMessageBody];
	[alert _slideSheetOut:YES];
	[alert setRunsModal:YES];
	[alert popupAlertAnimated:YES];
}

- (void) alertSheet:(UIAlertSheet *)aSheet buttonClicked:(int) aButton{
	[aSheet dismiss];
}

- (void)dealloc{
	[mWindow dealloc];
	mWindow=nil;

	[mView dealloc];
	mView=nil;

	[super dealloc];
}

- (void)navigationBar:(UINavigationBar *)aBar buttonClicked:(int)aButton{
	NSLog(@"Inside navigationBar: buttonClicked");
	switch(aButton){
		case 1: //About
			//TODO: Hack remove thise line!
			[self clearPhrases];
			[self showAlert:@"About" withMessageBody:@"\"iTally Wrapped with love from:\"\n\nMohamed El-Shinnawy\n(H&M)"];
			break;
		case 0: //Add
			[self savePhraseWithDescription:@"Hello" withPronounciation:@"Pronto"];
			break;
	}
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
	NSLog(@"Inside textFieldShouldReturn");
	[textField resignFirstResponder];
	return YES;
}

- (BOOL)keyboardInput:(id)k shouldInsertText:(id)i isMarkedText:(int)b{
	NSLog(@"keyboardInput:shouldInsertText:isMarkedText");
	NSLog(@"<%@>",i);
	if ([i characterAtIndex:0] == 0xA) {
   		NSLog(@"user return pressed");
		NSString * searchTerm = [mSearchBoxView text];
		if(searchTerm != nil && searchTerm.length > 0)
		{
			[self hideKeyboard];
			NSLog(@"Search term = %@", searchTerm);
			[mSearchBoxView resignFirstResponder];
			NSMutableArray * results = [self getResults: searchTerm];
		}
		else
		{
			NSLog(@"Search Term == nil || empty");
		}
                return NO;
	}
        return YES;
}

- (void)tableRowSelected:(NSNotification *)notification{
}

- (int)numberOfRowsInTable:(UITable *)table{
	return mResults == nil ? 0 : [mResults count];
}

- (UITableCell *)table:(UITable *)table cellForRow:(int)row column:(int)col{
	//Get transparent color for background
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
	float transparentComponents[4] = {0, 0, 0, 0};
	float grayComponents[4] = {0, 0, 0, 0.4};

	//Retrieve phrase
	Phrase *p = (Phrase *)[mResults objectAtIndex:row];

	//Add Pronounciation
	UIImageAndTextTableCell *cell = [[UIImageAndTextTableCell alloc] init];
	[cell setTitle: [p getPronounciation]];
	[cell setShowDisclosure:YES];
	[cell setDisclosureStyle:1];
	[[cell titleTextLabel] drawRect:CGRectMake(10.0f, -10.0f, 210.0f, 35.0f)];
	UITextLabel *activeLabel = [[UITextLabel alloc] initWithFrame:CGRectMake(10.0f, 45.0f, 210.0f, 30.0f)];
	[activeLabel setWrapsText:YES];
	[activeLabel setBackgroundColor:CGColorCreate(colorSpace, transparentComponents)];
	[activeLabel setText: [p getDescription]];
	[activeLabel setColor:CGColorCreate(colorSpace, grayComponents)];
	[cell addSubview: activeLabel];
	//Returning label
	return cell;
}

-(void)keyboardReturnPressed{
	[self hideKeyboard];
}

- (void) clearButtonClicked{
	if (!mIsKeyboardVisible)
	{
		[self showKeyboard];
	}
}

- (void) showKeyboard
{
	NSLog(@"Inside showKeyboard");
	mIsKeyboardVisible = YES;

	struct CGRect startFrame;
	struct CGRect endFrame;
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	NSMutableArray *animations = [[NSMutableArray alloc] init];
	
	endFrame = CGRectMake(rect.origin.x, rect.size.height - [UIKeyboard defaultSize].height, rect.size.width, [UIKeyboard defaultSize].height);
	startFrame = endFrame;
	startFrame.origin.y = 245.0 + 216.;
	
	[mKeyboard setFrame:startFrame];
	
	UIFrameAnimation *keyboardAnimation = [[UIFrameAnimation alloc] initWithTarget:mKeyboard];
	[keyboardAnimation setStartFrame:startFrame];
	[keyboardAnimation setEndFrame:endFrame];
	[keyboardAnimation setSignificantRectFields:2];
	[keyboardAnimation setDelegate:self];
	[animations addObject:keyboardAnimation];
	[keyboardAnimation release];
	
	[[UIAnimator sharedAnimator] addAnimations:animations withDuration:.75f start:YES];
}

- (void) hideKeyboard
{
	NSLog(@"Inside hideKeyboard");
	mIsKeyboardVisible = NO;
	
	struct CGRect startFrame;
	struct CGRect endFrame;
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	NSMutableArray *animations = [[NSMutableArray alloc] init];
	
	startFrame = CGRectMake(rect.origin.x, rect.size.height - [UIKeyboard defaultSize].height, rect.size.width, [UIKeyboard defaultSize].height);
	endFrame = startFrame;
	endFrame.origin.y = 245.0 + 216.;
	
	[mKeyboard setFrame:startFrame];
		
	UIFrameAnimation *keyboardAnimation = [[UIFrameAnimation alloc] initWithTarget:mKeyboard];
	[keyboardAnimation setStartFrame:startFrame];
	[keyboardAnimation setEndFrame:endFrame];
	[keyboardAnimation setSignificantRectFields:2];
	[keyboardAnimation setDelegate:self];
	[animations addObject:keyboardAnimation];
	[keyboardAnimation release];
	
	[[UIAnimator sharedAnimator] addAnimations:animations withDuration:.75f start:YES];
}

- (BOOL)respondsToSelector:(SEL)aSelector
{
	NSString *selectorText = NSStringFromSelector(aSelector);
	NSLog(@"Inside respondsToSelector: selector = %@", selectorText);
	if([selectorText isEqualToString:@"textFieldShouldStartEditing:"]){
		if(mIsAddingKeyboard) return [super respondsToSelector:aSelector];
		NSLog(@"Will now show keyboard!");
		[self showKeyboard];
	}
	return [super respondsToSelector:aSelector];
}
@end
